﻿using System;
using System.Collections.Generic;
using System.Text;

using Obsidian.Utils;

namespace Obsidian.Edm
{
    public class EntityField<T> : ModelField, IModelField where T : IModel, new()
    {

        public override FieldType Type
        {
            get { return FieldType.Entity; }
        }

        private T _value;
        /// <summary>
        /// 获取值
        /// </summary>
        public T Value
        {
            get
            {
                if (_isNull)
                    throw new Exception("空值状态无法获得该属性值");
                return this._value;
            }
        }


        /// <summary>
        /// 获取值
        /// </summary>
        public object OValue
        {
            get
            {
                if (_isNull) return null;
                else return _value;
            }
        }

        /// <summary>
        /// 设置值
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public IModel Set(T value)
        {
            if (!base._assigned)
                base._assigned = true;
            this._isNull = false;
            this._value = value;
            return base.Model;
        }

        /// <summary>
        /// 设置值
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public IModel Set(object value)
        {
            if (value == null)
            {
                return this.SetNull();
            }
            else
            {
                T val = (T)value;
                return this.Set(val);
            }
        }

        /// <summary>
        /// 设置值
        /// </summary>
        public bool TrySet(object value)
        {
            try
            {
                this.Set(value);
                return true;
            }
            catch
            {
                this.SetNull();
                return false;
            }

        }

        /// <summary>
        /// 设置为空值状态
        /// </summary>
        public IModel SetNull()
        {
            this._value = default(T);
            this._isNull = true;
            return base.Model;
        }

        public new string ToString()
        {
            return this.IsNull ? null : ModelUtil.ToJsonString(this._value);
        }
        
        public EntityField(IModel model)
        {
            this.InitField(model);
        }

        public EntityField(IModel model, string alias)
        {
            this.InitField(model, null, alias);
        }

        public EntityField(IModel model, string alias, T defaultValue)
        {
            this.InitField(model, null, alias);
            if (defaultValue != null)
            {
                this._value = defaultValue;
                this._isNull = false;
            }
        }

        public T New()
        {
            var o = new T();
            this.Set(o);
            return o;
        }
    }
}
